<template>
  <el-dialog title="打卡时间" :visible.sync="visible" v-if="visible" width="600px" append-to-body v-dialogDrag :close-on-click-modal="false">
    <div>
        <el-form ref="form" :rules="rules" v-if="!switchFlag" :model="form" label-width="100px">
          <el-form-item label="工作日:" prop="checkedWeeks">
            <el-checkbox-group size="mini" @change="getWeekString(form.checkedWeeks)" v-model="form.checkedWeeks">
              <el-checkbox v-for="week in weekdays" :disabled="week.disabled" :label="week.value" :key="week.value" :value="week.value">{{week.label}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item prop="timeArray" label="打卡时间:">
<!--              <i class="el-icon-remove hoverConfirm" @click="deleteTimeArray(item)" v-if="form.timeArray.length!=1" style="font-size: 25px; margin-left: 10px; margin-bottom: 5px;"></i>-->
<!--              <i class="el-icon-circle-plus hoverConfirm" @click="addTimeArray" v-if="form.timeArray.indexOf(item)==form.timeArray.length-1&&form.timeArray.length!=4" style="font-size: 25px; margin-left: 10px; margin-bottom: 5px;"></i>-->
            <span style="margin-left: 10px">上班</span>
            <el-time-picker
              style="width: 100px;margin-left: 10px"
              value-format="HH:mm"
              format="HH:mm"
              @change="checkTimeRange"
              v-model="form.timeArray.startTime"
              placeholder="任意时间点">
            </el-time-picker>
            <span style="margin-left: 10px">—下班</span>
            <el-time-picker
              style="width: 100px;margin-left: 10px"
              value-format="HH:mm"
              format="HH:mm"
              @change="checkTimeRange"
              v-model="form.timeArray.endTime"
              placeholder="任意时间点">
            </el-time-picker>
            <span v-if="form.timeArray.timeRangeError" style="color: red; margin-left: 10px">开始时间必须小于结束时间</span>
          </el-form-item>
          <el-form-item label="打卡时段设置:">
            <span>{{this.form.timeArray.periodList[0].startTime}}-{{this.form.timeArray.periodList[1].endTime}}可打卡</span>
            <a style="margin-left: 10px" @click="updateSwitch">修改</a>
            <span v-if="form.timeArray.periodError" style="color: red; margin-left: 10px">{{form.timeArray.periodError}}</span>
            <br>
            <span style="font-size: 12px;color: grey;margin-top: 2px;">可设置每次上下班是否需要打卡、允许打卡的时间范围。</span>
          </el-form-item>
          <el-form-item label="休息时间:">
            <el-checkbox v-model="form.enableRest">开启</el-checkbox>
            <span style="font-size: 12px;color: grey;margin-top: 2px;">休息时间内不计算工作时长</span>
            <div v-if="form.enableRest">
              <span style="margin-left: 10px">开始</span>
              <el-time-picker
                style="width: 100px;margin-left: 10px"
                value-format="HH:mm"
                format="HH:mm"
                @change="checkTimeRange"
                v-model="form.restTime.startTime"
                placeholder="任意时间点">
              </el-time-picker>
              <span style="margin-left: 10px">— 结束</span>
              <el-time-picker
                style="width: 100px;margin-left: 10px"
                value-format="HH:mm"
                format="HH:mm"
                @change="checkTimeRange"
                v-model="form.restTime.endTime"
                placeholder="任意时间点">
              </el-time-picker>
              <br/>
              <span v-if="form.restTime.restError" style="color: red; margin-left: 10px">休息开始时间必须小于结束时间</span>
            </div>
          </el-form-item>
          <el-form-item label="弹性上下班:">
            <el-checkbox v-model="form.enableStress">开启</el-checkbox>
            <br>
            <el-radio v-model="form.stressRadio" label="1" v-if="form.enableStress">允许迟到早退</el-radio>
            <br>
            <div v-if="form.stressRadio==1">
<!--              <el-radio v-model="form.stressRadio" label="2">备选项</el-radio>-->
              <span style="margin-left: 10px">上班允许迟到</span>
              <select v-model="form.leaveEarlyMinutes.startMinutes">
                <option v-for="option in minutesOptions" :value="option.value">{{ option.text }}</option>
              </select>
              <span style="margin-left: 10px">,下班允许早退</span>
              <select v-model="form.leaveEarlyMinutes.endMinutes">
                <option v-for="option in minutesOptions" :value="option.value">{{ option.text }}</option>
              </select>
              <br/>
            </div>
            <el-radio v-model="form.stressRadio" label="2" v-if="form.enableStress">允许早到早走、晚到晚走</el-radio>
            <div v-if="form.stressRadio==2">
              <span style="margin-left: 10px">最多早到早走</span>
              <select v-model="form.mostLeaveMinutes.startMinutes">
                <option v-for="option in minutesOptions" :value="option.value">{{ option.text }}</option>
              </select>
              <span style="margin-left: 10px">,最多晚到晚走</span>
              <select v-model="form.mostLeaveMinutes.endMinutes">
                <option v-for="option in minutesOptions" :value="option.value">{{ option.text }}</option>
              </select>
              <br/>
            </div>
            <br>
          </el-form-item>
          <div>
            <a style="margin-left: 10px" @click="majorSettingChange">高级设置
              <i class="el-icon-arrow-down" v-if="!form.majorSetting" style="margin-left: 5px"></i>
              <i class="el-icon-arrow-up" v-if="form.majorSetting" style="margin-left: 5px"></i>
            </a>
          </div>
          <el-form-item label="下班晚走,次日晚到:" label-width="140px" v-if="form.majorSetting">
            <el-checkbox v-model="form.enableArriveLate">开启</el-checkbox>
            <div v-if="form.enableArriveLate" v-for="item in form.arriveLateList">
              <span style="margin-left: 10px">下班晚走</span>
              <select v-model="item.leavesLateMin">
                <option v-for="option in minutesOptions" :value="option.value">{{ option.text }}</option>
              </select>
              <span style="margin-left: 10px">,次日可晚到</span>
              <select v-model="item.lateMin">
                <option v-for="option in minutesOptions" :value="option.value">{{ option.text }}</option>
              </select>
              <a style="margin-left: 10px"  @click="deleteArriveLate(item)" v-if="form.arriveLateList.length!=1">删除</a>
              <a style="margin-left: 10px"  @click="addArriveLate" v-if="form.arriveLateList.indexOf(item)==form.arriveLateList.length-1&&item.leavesLateMin!=minutesOptions[minutesOptions.length-1].value">新增条件</a>
            </div>
            <br/>
          </el-form-item>
        </el-form>
        <el-form ref="clockRange" v-if="switchFlag" :model="temp" label-width="90px">
          <el-form-item label="上下班时段">
            <span style="margin-left: 10px">上班</span>
            <span style="margin-left: 5px" v-if="temp.flag">{{temp.startTime}}</span>
            <el-time-picker
              style="width: 100px;margin-left: 10px"
              value-format="HH:mm"
              format="HH:mm"
              v-if="!temp.flag"
              v-model="temp.startTime"
              @change="checkTempTimeRange"
              placeholder="任意时间点">
            </el-time-picker>
            <span style="margin-left: 10px">—下班</span>
            <span style="margin-left: 5px" v-if="temp.flag">{{temp.endTime}}</span>
            <el-time-picker
              style="width: 100px;margin-left: 10px"
              v-if="!temp.flag"
              value-format="HH:mm"
              format="HH:mm"
              v-model="temp.endTime"
              @change="checkTempTimeRange"
              placeholder="任意时间点">
            </el-time-picker>
            <i class="el-icon-edit hoverConfirm" v-if="temp.flag" @click="temp.flag=false"  style="font-size: 15px; margin-left: 10px;"></i>
            <span v-if="temp.timeRangeError" style="color: red; margin-left: 10px">开始时间必须小于结束时间</span>
          </el-form-item>
          <el-table :data="temp.periodList" >
            <el-table-column prop="isClock" label="是否打卡" align="center" width="150">
              <template slot-scope="scope">
                <!-- `checked` 为 true 或 false -->
                <el-checkbox v-model="scope.row.isClock">{{scope.row.clockContent}}</el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="itemName" label="允许打卡时间范围">
              <template slot-scope="scope">
                <span>可打卡时间</span>
                <el-time-picker
                  style="width: 100px;margin-left: 10px"
                  value-format="HH:mm"
                  format="HH:mm"
                  @change="checkTempTimeRange"
                  v-model="scope.row.startTime"
                  placeholder="任意时间点">
                </el-time-picker>
                <span style="margin-left: 5px">至</span>
                <el-time-picker
                  style="width: 100px;margin-left: 10px"
                  value-format="HH:mm"
                  format="HH:mm"
                  @change="checkTempTimeRange"
                  v-model="scope.row.endTime"
                  placeholder="任意时间点">
                </el-time-picker>
              </template>
            </el-table-column>
          </el-table>
          <span v-if="temp.periodError" style="color: red; margin-left: 10px">{{temp.periodError}}</span>
        </el-form>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button size="small" v-if="switchFlag==false" type="primary" @click="confirmUser">确认</el-button>
      <el-button size="small" v-if="switchFlag==false"  @click="cancel">取 消</el-button>
      <el-button size="small" v-if="switchFlag==true" type="primary"  @click="switchConfirm">确认修改</el-button>
      <el-button size="small" v-if="switchFlag==true"  @click="switchCancel">不修改</el-button>
    </div>
  </el-dialog>
</template>

<script>

export default {
  props: {
    //回显的数据
    forbidList: {
      type: Array,
      default:()=>[]
    },
    clockTimeData:{
      type:Object,
      default:()=>{}
    },
  },
  name: "clockTime",
  dicts: ['sys_user_sex','employment_status'],
  data() {
    return {
      isdisabled:false,
      form:{
        timeArray: {
          startTime:"08:30",
          endTime:"17:30",
          periodClass:"上下班时段",
          flag:true,
          timeRangeError: false,
          periodError:"",
          periodList:[
            {
              isClock:true,
              clockContent:"上班需要打卡",
              startTime:"04:00",
              endTime:"16:59"
            },
            {
              isClock:true,
              clockContent:"下班需要打卡",
              startTime:"09:01",
              endTime:"20:59"
            }
          ]
        },
        result:"",
        checkedWeeks: [],
        enableRest:false,
        restTime:{
          startTime:"11:20",
          endTime:"13:30",
          restError:false
        },
        enableStress:false,
        stressRadio:"",
        leaveEarlyMinutes:{
          startMinutes:"0",
          endMinutes:"0",
        },
        mostLeaveMinutes:{
          startMinutes:"0",
          endMinutes:"0",
        },
        majorSetting:false,
        enableArriveLate:false,
        "arriveLateList":[
          {
            "leavesLateMin":"60",
            "lateMin":"60"
          }
        ],
        //位于原集合位置
        index:-1,
      },
      temp:{},
      // 遮罩层
      loading: true,
      visible: false,
      switchFlag:false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      rules:{
        checkedWeeks: [
          { required: true, message: "工作日不能为空", trigger: "blur" }
        ],
        timeArray:[
          { required: true, message: "日期不能为空", trigger: "blur" }
        ]
      },
      weekdays: [
        {
        label: "星期一",
        value: 1,
        disabled:false,
      }, {
        label: "星期二",
        value: 2,
        disabled:false,
      }, {
        label: "星期三",
        value: 3,
        disabled:false,
      }, {
        label: "星期四",
        value: 4,
        disabled:false,
      }, {
        label: "星期五",
        value: 5,
        disabled:false,
      }, {
        label: "星期六",
        value: 6,
        disabled:false,
      }, {
        label: "星期日",
        value: 7,
        disabled:false,
      }],
      userList: [],
      checkedDepList:[],
      // 部门树选项
      deptOptions: [],
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        deptId: undefined,
        type: 'person',
        ids:[]
      },
      flag: false,
      minutesOptions: [
        { value: "0", text: "0分钟" },
        { value: "5", text: "5分钟" },
        { value: "10", text: "10分钟" },
        { value: "15", text: "15分钟" },
        { value: "20", text: "20分钟" },
        { value: "30", text: "30分钟" },
        { value: "45", text: "45分钟" },
        { value: "60", text: "60分钟" },
        { value: "90", text: "90分钟" },
        { value: "120", text: "120分钟" },
        { value: "150", text: "150分钟" },
        { value: "180", text: "180分钟" },
        // 其他选项
      ],
    };
  },
  watch: {
    forbidList(val){
      if (val){
        this.weekdays.forEach(d=>{
          if (val.indexOf(d.value)!=-1){
            d.disabled=true;
          }else {
            d.disabled=false;
          }
        })
      }
    },
    visible(val){
      if (val){
        if (this.clockTimeData.checkedWeeks){
          this.form=this.clockTimeData;
        }
      }
    }
  },
  created() {
  },
  methods: {
    confirmUser(){
      if (!this.form.result){
        this.$message.error('至少要选择一个工作日');
        return;
      }
      if (this.form.timeArray.timeRangeError||this.form.restTime.restError){
        return
      }
      this.$emit('confirmUser', this.form)
      this.form = {
        timeArray: {
          startTime: "09:00",
          endTime: "17:00",
          periodClass: "上下班时段",
          flag: true,
          timeRangeError: false,
          periodError: "",
          periodList: [
            {
              isClock: true,
              clockContent: "上班需要打卡",
              startTime: "04:00",
              endTime: "16:59"
            },
            {
              isClock: true,
              clockContent: "下班需要打卡",
              startTime: "09:01",
              endTime: "20:59"
            }
          ]
        },
        result: "",
        checkedWeeks: [],
        enableRest: false,
        restTime: {
          startTime: "09:00",
          endTime: "17:00",
          restError: false
        },
        enableStress: false,
        stressRadio: "",
        leaveEarlyMinutes: {
          startMinutes: "0",
          endMinutes: "0",
        },
        mostLeaveMinutes: {
          startMinutes: "0",
          endMinutes: "0",
        },
        majorSetting: false,
        enableArriveLate: false,
        "arriveLateList": [
          {
            "leavesLateMin": "60",
            "lateMin": "60"
          }
        ],
        index:-1,
      };
      this.visible = false;
    },
    getWeekString(arr) {
      const weekArray = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
      arr.sort(function(a, b) {
        return a - b;
      });
      let result = "";
      let start = -1;
      let end = -1;
      for (let i = 0; i < arr.length; i++) {
        if (start === -1) {
          start = arr[i];
          end = arr[i];
        } else if (arr[i] === end + 1) {
          end = arr[i];
        } else {
          if (start === end) {
            result += weekArray[start - 1] + "、";
          } else if (end - start === 1) {
            result += weekArray[start - 1] + "、" + weekArray[end - 1] + "、";
          } else {
            result += weekArray[start - 1] + "至" + weekArray[end - 1] + "、";
          }
          start = arr[i];
          end = arr[i];
        }
      }

      if (start !== -1) {
        if (start === end) {
          result += weekArray[start - 1];
        } else if (end - start === 1) {
          result += weekArray[start - 1] + "、" + weekArray[end - 1];
        } else {
          result += weekArray[start - 1] + "至" + weekArray[end - 1];
        }
      }
      this.form.result=result;
    },
    addTimeArray() {
      const lastWorkTime = this.form.timeArray[this.form.timeArray.length - 1];
      const newStartTime = this.incrementTime(lastWorkTime.endTime, 60);
      const newEndTime = this.incrementTime(newStartTime, 60);
      console.log(this.incrementTime(newStartTime, -1))

      const newWorkTime = {
        startTime: newStartTime,
        endTime: newEndTime,
        flag: true,
        periodClass: "上下班时段" + (this.form.timeArray.length + 1),
        periodList: [
          {
            isClock: true,
            clockContent: "上班需要打卡",
            startTime: this.incrementTime(newStartTime, -30),
            endTime: this.incrementTime(newStartTime, -1)
          },
          {
            isClock: true,
            clockContent: "下班需要打卡",
            startTime: this.incrementTime(newStartTime, 1),
            endTime: "23:59"
          }
        ]
      };
      console.log(this.form.timeArray)
      this.form.timeArray.push(newWorkTime);
      // 更新倒数第二条的下班打卡要求的endTime
      if (this.form.timeArray.length >= 2) {
        let secondLastWorkTime = this.form.timeArray[this.form.timeArray.length - 2];
        let secondLastPeriodList = secondLastWorkTime.periodList;
        secondLastPeriodList[1].endTime = this.incrementTime(newStartTime, -30);
        this.form.timeArray[this.form.timeArray.length - 2].periodList=secondLastPeriodList;
        console.log(this.form.timeArray)
      }

    },
    incrementTime(time, minutes) {
      const [hours, mins] = time.split(":");
      const date = new Date();
      date.setHours(hours);
      date.setMinutes(mins);
      date.setMinutes(date.getMinutes() + minutes);
      return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
    },
    deleteTimeArray(item){
      const index = this.form.timeArray.indexOf(item); // 获取要删除项的索引
      if (index !== -1) {
        this.form.timeArray.splice(index, 1); // 从数组中删除对应项
      }
    },
    deleteArriveLate(item){
      const index = this.form.arriveLateList.indexOf(item); // 获取要删除项的索引
      if (index !== -1) {
        this.form.arriveLateList.splice(index, 1); // 从数组中删除对应项
      }
    },
    addArriveLate(){
      let last=this.form.arriveLateList[this.form.arriveLateList.length-1];
      let data=this.minutesOptions.filter(d=>d.value==last.leavesLateMin);
      if (data){
        let index=this.minutesOptions.indexOf(data[0]);
        if (index!=this.minutesOptions.length-1){
          this.form.arriveLateList.push({
            "leavesLateMin":this.minutesOptions[index+1].value,
            "lateMin":this.minutesOptions[index+1].value,
          });
        }else {
          this.form.arriveLateList.push(last)
        }
      }else {
        this.form.arriveLateList.push(last)
      }
    },
    updateSwitch(){
      this.switchFlag=true;
      this.temp = JSON.parse(JSON.stringify(this.form.timeArray));
      this.checkTempTimeRange();
    },
    addOneHour(timeString) {
      const [hours, minutes] = timeString.split(':');
      const date = new Date();
      date.setHours(parseInt(hours));
      date.setMinutes(parseInt(minutes));
      date.setHours(date.getHours() + 1);
      const newHours = date.getHours();
      const newMinutes = date.getMinutes();
      const newTimeString = `${newHours.toString().padStart(2, '0')}:${newMinutes.toString().padStart(2, '0')}`;
      return newTimeString;
    },
    switchCancel(){
      this.switchFlag=false;
      this.temp="";
      // this.form.timeArray.forEach(d=>{
      //   d.flag=true;
      // })
    },
    switchConfirm(){
      if (this.temp.periodError||this.temp.timeRangeError||this.form.timeArray.periodError){
        return
      }
      this.form.timeArray = JSON.parse(JSON.stringify(this.temp));
      this.switchFlag=false;
      this.temp="";
    },
    majorSettingChange(){
      this.form.majorSetting=!this.form.majorSetting;
    },
    addTimePicker() {
      this.form.timeArray.push([]);
      console.log(this.form.timeArray)
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        weekDays:undefined,
      };
      this.resetForm("form");
    },
    cancel() {
      this.switchFlag = false;
      this.visible = false;
      this.form = {
        timeArray: {
          startTime: "09:00",
          endTime: "17:00",
          periodClass: "上下班时段",
          flag: true,
          timeRangeError: false,
          periodError: "",
          periodList: [
            {
              isClock: true,
              clockContent: "上班需要打卡",
              startTime: "04:00",
              endTime: "16:59"
            },
            {
              isClock: true,
              clockContent: "下班需要打卡",
              startTime: "09:01",
              endTime: "20:59"
            }
          ]
        },
        result: "",
        checkedWeeks: [],
        enableRest: false,
        restTime: {
          startTime: "09:00",
          endTime: "17:00",
          restError: false
        },
        enableStress: false,
        stressRadio: "",
        leaveEarlyMinutes: {
          startMinutes: "0",
          endMinutes: "0",
        },
        mostLeaveMinutes: {
          startMinutes: "0",
          endMinutes: "0",
        },
        majorSetting: false,
        enableArriveLate: false,
        "arriveLateList": [
          {
            "leavesLateMin": "60",
            "lateMin": "60"
          }
        ],
      };
    },
    checkTimeRange() {
      if (this.form.timeArray.startTime && this.form.timeArray.endTime) {
        if (this.form.timeArray.startTime >= this.form.timeArray.endTime) {
          this.form.timeArray.timeRangeError = true
        } else {
          this.form.timeArray.timeRangeError = false
        }
      } else {
        this.form.timeArray.timeRangeError = false
      }
      if (this.form.timeArray.periodList[0].startTime>this.form.timeArray.startTime) {
        this.form.timeArray.periodError = "打卡时间限制应早于上班时间" + this.form.timeArray.startTime + ",请修改"
      }else if (this.form.timeArray.periodList[1].endTime<this.form.timeArray.endTime){
        this.form.timeArray.periodError="打卡时间限制应晚于下班时间"+this.form.timeArray.endTime+",请修改"
      }else {
        this.form.timeArray.periodError=''
      }
      if (this.form.restTime.startTime && this.form.restTime.endTime) {
        if (this.form.restTime.startTime >= this.form.restTime.endTime) {
          this.form.restTime.restError = true
        } else {
          this.form.restTime.restError = false
        }
      } else {
        this.form.restTime.restError = false
      }
    },
    checkTempTimeRange() {
      if (this.temp.startTime && this.temp.endTime) {
        if (this.temp.startTime >= this.temp.endTime) {
          this.temp.timeRangeError = true
        } else {
          this.temp.timeRangeError = false
        }
      } else {
        this.temp.timeRangeError = false
      }
      if (this.temp.periodList[0].startTime>this.temp.startTime) {
        this.temp.periodError = "打卡时间限制应早于上班时间" + this.temp.startTime + ",请修改"
      }else if (this.temp.periodList[1].endTime<this.temp.endTime){
        this.temp.periodError="打卡时间限制应晚于下班时间"+this.temp.endTime+",请修改"
      }else {
        this.temp.periodError=''
      }
    },
  }
};
</script>
<style scoped>
  .el-checkbox-group .el-checkbox {
    margin-right: 5px;
  }
  .el-table th,
  .el-table td {
    border: 1px solid #dde;
    padding: 8px;
  }
  ::v-deep .custom-time-picker .el-icon-circle-close {
    display: none !important;
  }
  .hoverConfirm:hover {
    cursor: pointer;
  }
</style>
